



//
//  LJHCateScrollViewController.m
//  HEARME
//
//  Created by liujinhui on 16/1/27.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LJHCateScrollViewController.h"
#import "LJHCateScrollView.h"
#import "LJHChildListModel.h"
#import "LJHCateScrollTableView.h"
#import "LJHContentTableViewCell.h"
#import "LJHAlbumsDetailCell.h"
#import "MJRefresh.h"
#import "LJHAlbumModel.h"
#import "LJHAlbumsDetailViewController.h"
#import "LJHAlbumListTableViewCell.h"
@interface LJHCateScrollViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate,CategoryScrollDelegate>

@property(nonatomic,retain)LJHCateScrollView *homeView;

@end

@implementation LJHCateScrollViewController

- (void)dealloc
{
    [_homeView release];
    [super dealloc];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setTranslucent:NO];
    
    [LJHPlayBtn shareButton].frame =CGRectMake(WIDTH*0.4, HEIGHT-WIDTH*0.2-64, WIDTH*0.2, WIDTH*0.35);
    [self.view addSubview :[LJHPlayBtn shareButton]];
    [[LJHPlayBtn shareButton].musicBtn addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [super viewWillAppear:animated];
    if ([LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePlaying) {
        
        
        [[LJHPlayBtn shareButton] startCircle];
    }
    if ([LJHPlayerViewController sharaMusicPlayer].player.state == STKAudioPlayerStatePaused) {
        
        [[LJHPlayBtn shareButton] stopCircle];
        
    }
    
    [self upTableView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self getTitleData];
    [GiFHUD setGifWithImageName:@"loading.gif"];
    [GiFHUD show];
    
    //返回按钮
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 0 , 20, 30);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[UIImage imageNamed:@"btn_back_n@2x.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_h@2x.png"] forState:UIControlStateHighlighted];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
}
#pragma mark - playButton
-(void)buttonAction:(UIButton *)btn
{
    
    LJHPlayerViewController *player = [LJHPlayerViewController sharaMusicPlayer];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:player];
    [self.view.window.rootViewController presentViewController:naVC animated:YES completion:^{
        
    }];
    
}


#pragma mark - 返回按钮方法
-(void)backButtonAction:(UIButton *)btn
{
    
    [self.navigationController  popViewControllerAnimated:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"createBigButton" object:[LJHPlayBtn shareButton]];
    
}

#pragma mark - 通过上一页传过来的标题获取本页按钮和scrollView的个数和内容
-(void)getTitleData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/category/tagsWithoutCover?categoryId=%@&contentType=album&device=iphone", self.categoryId];
    //    NSLog(@"%@", _categoryId);
    [LJHAppTools afnGetRequest:urlStr block:^(id result) {
        
        if (result == NULL) {
            
        }
        else{
            self.titleArray = [NSMutableArray array];
            NSMutableArray *array = [result objectForKey:@"list"];
            for (NSMutableDictionary *dic in array) {
                LJHChildListModel *model = [LJHChildListModel modelWithDictionary:dic];
                [self.titleArray addObject:model.tname];
            }
            
            //创建外层ScrollView
            self.homeView = [[LJHCateScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64)];
            self.homeView.myDelegate = self;
            [self.view addSubview:self.homeView];
            self.currentTag = 0;
            //通过按钮标题设置按钮scrollView
            [self.homeView setTitleContent:_titleArray];
            
            //创建和按钮对应的tableView
            self.tableViewArray = [NSMutableArray array];
            self.currentIndex = 0;
            
            for (int i = 0; i < array.count; i++) {
                
                LJHCateScrollTableView *tableView = [[LJHCateScrollTableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64) style:UITableViewStylePlain];
                [self.tableViewArray addObject:tableView];
            }
            [self.homeView setBgScrollViewContents:self.tableViewArray];
            
            self.currentTableV = [self.tableViewArray objectAtIndex:0];
            [self initTableView];
            
        }
        
    } error:^(NSError *error) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"您的设备无网络访问" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertC addAction:cancelButton];
    }];
}

#pragma mark - 初始化tableView
- (void)initTableView{
    
    if (self.currentTableV.dataArray.count > 0) {
        return;
    }
    //    [self initSDCycle];
    self.currentPage = 1;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(upTableView)];
    self.currentTableV.header = header;
    self.currentTableV.delegate = self;
    self.currentTableV.dataSource = self;
    [self.currentTableV registerClass:[LJHAlbumListTableViewCell class] forCellReuseIdentifier:@"categoryTableCell"];
    self.currentTableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.currentTableV.header beginRefreshing];
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(downTableView)];
    self.currentTableV.footer = footer;
    
    [self.view bringSubviewToFront:[LJHPlayBtn shareButton]];
    
}

#pragma mark - 下拉刷新
- (void)upTableView{
    
    self.currentPage = 1;
    NSString *title = [self.titleArray objectAtIndex:self.currentTag];
    NSString *http = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=%@&device=iphone&pageId=%ld&pageSize=20&status=0&tagName=%@", self.categoryId, self.currentPage, title];
    NSLog(@"%@", http);
    self.currentIndex = 0;
    [self addData: http andDwon:NO];
}

#pragma mark - 上拉刷新
- (void)downTableView{
    
    NSString *title = [self.titleArray objectAtIndex:self.currentTag];
    NSString *http = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=%@&device=iphone&pageId=%ld&pageSize=20&status=0&tagName=%@", self.categoryId, self.currentPage+1, title];
//    NSLog(@"%@%ld%@",self.categoryId,self.currentPage+1,title);
    self.currentIndex = self.currentTableV.dataArray.count;
    [self addData:http andDwon:YES];
}
- (void)addData:(NSString *)url andDwon:(BOOL)isDown
{
    
    
    [LJHAppTools afnGetRequest:url block:^(id result) {
        
        //        NSLog(@"%@", result);
        NSMutableArray *array = [result objectForKey:@"list"];
        
        if (!isDown) {
            self.currentTableV.dataArray = [NSMutableArray array];
        }
        
        for (NSMutableDictionary *dic in array) {
            
            LJHAlbumModel *model = [LJHAlbumModel modelWithDictionary:dic];
            model.isFavor = NO;
            
            
            if ([[[LJHFMData shareFMDB] selectAlbumIdData] containsObject:model.myId]) {
                model.isFavor = YES;
            }
            
            [self.currentTableV.dataArray addObject:model];
            
            
        }
        
        if (isDown) {
            self.currentPage++;
        }
        
        [self.currentTableV reloadData];
        [self.currentTableV.header endRefreshing];
        [self.currentTableV.footer endRefreshing];
        
    } error:^(NSError *error) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"您的设备无网络访问" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertC addAction:cancelButton];
    }];
    
}

#pragma mark - tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.currentTableV.dataArray.count - 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    LJHAlbumListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryTableCell"];
    
    cell.albumModel = (LJHAlbumModel *)self.currentTableV.dataArray[indexPath.row];
    
    return cell;
//    LJHContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"categoryTableCell"];
//    
//    cell.albumModel = (LJHAlbumModel *)self.currentTableV.dataArray[indexPath.row];
//    
//    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return WIDTH*0.3;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    LJHAlbumsDetailViewController *albumsDetailVC = [[LJHAlbumsDetailViewController alloc] init];
    
    albumsDetailVC.albumId = ((LJHAlbumModel *)self.currentTableV.dataArray[indexPath.row]).myId;
    //    albumsDetailVC.myTitle = _myTitle;
    albumsDetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:albumsDetailVC animated:YES];
//    NSLog(@"1111111111111111");
    
}

#pragma mark - scrollView拖拽结束时触发方法
- (void)endDraggingAction:(NSInteger)tag{
    
    self.currentTag = tag;
    
    self.currentTableV = [self.tableViewArray objectAtIndex:self.currentTag];
    
    if (self.currentTableV.header != nil) {
        return;
    }
    
    [self initTableView];
}

- (void)titleButtonAction:(UIButton *)button{
    
    self.currentTag = button.tag - 1000;
    
    self.currentTableV = [self.tableViewArray objectAtIndex:self.currentTag];
    
    if (self.currentTableV.header != nil) {
        return;
    }
    
    [self initTableView];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
